package com.azt.data.action;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.azt.data.permission.MenuPermission;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.azt.api.model.Pagination;
import com.azt.api.service.PaginationService;
import com.azt.data.utils.CommonUtil;
import com.azt.data.utils.ExcelExportEntityUtil;
import com.azt.data.utils.Globals;
import com.azt.data.utils.RequestUtils;
import com.azt.provider.mapper.TradeMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xiaoleilu.hutool.util.StrUtil;

import net.sf.json.JSONArray;

/**
 * @ClassName: TradeAction
 * @Description: 平台交易
 * @author: zhaheng
 * @date: 2017年4月25日 上午9:41:23
 */
@Controller
@RequestMapping(value = "/trade")
public class TradeAction {

	@Autowired
	private TradeMapper tradeMapper;

	@Autowired
	private PaginationService paginationService;

	/** 交易概览开始 **/
	@MenuPermission
	@RequestMapping(value = "/tradeview")
	public String tradeview(ModelMap model) {
		// 当前平台交易总金额
		String tradeTotal = new BigDecimal(tradeMapper.getTradeTotal()).divide(new BigDecimal("100000000")).setScale( 2 , BigDecimal.ROUND_HALF_UP).toString() + "亿";
		// 当前参与交易采购商总数
		int tradePurchaserCount = tradeMapper.getTradePurchaserCount();
		// 当前参与交易供应商总数
		int tradeProviderCount = tradeMapper.getTradeProviderCount();
		// 当前已完成订单总数
		int tradeCount = tradeMapper.getTradeCount();
		double pinganTotal = tradeMapper.getPinganTotalPay();
		model.addAttribute("tradeTotal", tradeTotal);
		model.addAttribute("tradeCount", tradeCount);
		model.addAttribute("tradePurchaserCount", tradePurchaserCount);
		model.addAttribute("tradeProviderCount", tradeProviderCount);
		model.addAttribute("pinganTotal", pinganTotal);
		return "trade/tradeview";
	}

	/**
	 * @Title: getTradeOrderRate
	 * @Description: 总订单数量及增长率
	 * @return
	 * @return: JSONObject
	 * @author: 查恒 2017年4月26日 下午1:57:59
	 */
	@ResponseBody
	@RequestMapping(value = "/getTradeOrderCountRate")
	public JSONObject getTradeOrderRate(String startDate, String endDate) {
		JSONObject json = new JSONObject();
		Calendar c = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		if (StrUtil.isBlank(startDate)) {
			endDate = sdf.format(c.getTime());
			c.add(Calendar.MONTH, -11);
			startDate = sdf.format(c.getTime());
		}
		List<Map<String, Object>> countRateList = tradeMapper.getTradeOrderCountRate(startDate, endDate);
		String jsonString = JSON.toJSONString(countRateList, CommonUtil.jsonfilter,
				SerializerFeature.WriteDateUseDateFormat);
		JSONArray fromObject = JSONArray.fromObject(jsonString);
		json.put("data", fromObject);
		json.put("startDate", startDate);
		json.put("endDate", endDate);
		return json;
	}

	/**
	 * @Title: tradeOrderTotalRate
	 * @Description: 订单总金额及增长率
	 * @return
	 * @return: JSONObject
	 * @author: 查恒 2017年4月26日 下午4:04:52
	 */
	@ResponseBody
	@RequestMapping(value = "/getTradeOrderTotalRate")
	public JSONObject tradeOrderTotalRate(String startDate, String endDate) {
		JSONObject json = new JSONObject();
		Calendar c = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		if (StrUtil.isBlank(startDate)) {
			endDate = sdf.format(c.getTime());
			c.add(Calendar.MONTH, -11);
			startDate = sdf.format(c.getTime());
		}
		List<Map<String, Object>> totalRateList = tradeMapper.getTradeOrderTotalRate(startDate, endDate);
		String jsonString = JSON.toJSONString(totalRateList, CommonUtil.jsonfilter,
				SerializerFeature.WriteDateUseDateFormat);
		JSONArray fromObject = JSONArray.fromObject(jsonString);
		json.put("data", fromObject);
		json.put("startDate", startDate);
		json.put("endDate", endDate);
		return json;
	}

	/**
	 * @Title: getTradeOrderCountTotalRate
	 * @Description: 自盈商城和第三方商铺
	 * @return
	 * @return: JSONObject
	 * @author: 查恒 2017年4月27日 上午9:07:38
	 */
	@ResponseBody
	@RequestMapping(value = "/getTradeOrderCountTotalRate")
	public JSONObject getTradeOrderCountTotalRate(String startDate, String endDate) {
		JSONObject json = new JSONObject();
		Calendar c = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		if (StrUtil.isBlank(startDate)) {
			endDate = sdf.format(c.getTime());
			c.add(Calendar.MONTH, -11);
			startDate = sdf.format(c.getTime());
		}
		List<Map<String, Object>> countTotalRateList = tradeMapper.getTradeOrderCountTotalRate(startDate, endDate);
		String jsonString = JSON.toJSONString(countTotalRateList, CommonUtil.jsonfilter,
				SerializerFeature.WriteDateUseDateFormat);
		JSONArray fromObject = JSONArray.fromObject(jsonString);
		json.put("data", fromObject);
		json.put("startDate", startDate);
		json.put("endDate", endDate);
		return json;
	}

	/**
	 * @Title: exportTradeDetailData
	 * @Description: 导出Excel表格
	 * @param type
	 * @param request
	 * @param response
	 * @return: void
	 * @author: 查恒 2017年4月27日 下午2:25:17
	 */
	@RequestMapping("/exporTradeDetailExcel")
	public void exportTradeDetailData(Integer type, String startDate, String endDate, HttpServletRequest request,
			HttpServletResponse response) {
		Workbook exportExcel = null;
		List<Map<String, Object>> selectList = null;
		String title = ".xls";
		if (type.equals(0)) {
			// 总订单数量及增长率
			selectList = tradeMapper.getTradeOrderCountRate(startDate, endDate);
			exportExcel = ExcelExportUtil.exportExcel(
					new ExportParams(ExcelExportEntityUtil.TRADE_VIEW_TITLE, "总订单数量及增长率", "总订单数量及增长率"),
					ExcelExportEntityUtil.TradeOrderCountRateList(), selectList);
			title = ExcelExportEntityUtil.TRADE_VIEW_TITLE + "总订单数量及增长率" + title;
		} else if (type.equals(1)) {
			// 订单总金额及增长率
			selectList = tradeMapper.getTradeOrderTotalRate(startDate, endDate);
			exportExcel = ExcelExportUtil.exportExcel(
					new ExportParams(ExcelExportEntityUtil.TRADE_VIEW_TITLE, "订单总金额及增长率", "订单总金额及增长率"),
					ExcelExportEntityUtil.TradeOrderTotalRateList(), selectList);
			title = ExcelExportEntityUtil.TRADE_VIEW_TITLE + "订单总金额及增长率" + title;
		} else if (type.equals(2)) {
			// 自盈商城和第三方商铺
			selectList = tradeMapper.getTradeOrderCountTotalRate(startDate, endDate);
			exportExcel = ExcelExportUtil.exportExcel(
					new ExportParams(ExcelExportEntityUtil.TRADE_VIEW_TITLE, "自盈商城和第三方商铺", "自盈商城和第三方商铺"),
					ExcelExportEntityUtil.TradeOrderCountTotalRateList(), selectList);
			title = ExcelExportEntityUtil.TRADE_VIEW_TITLE + "自盈商城和第三方商铺" + title;
		}

		try {
			response.setContentType("application/vnd.ms-excel;");
			response.setHeader("Content-Disposition", "attachment;filename=" + CommonUtil.toUtf8String(request.getHeader("User-Agent") , title));
			ServletOutputStream outputStream = response.getOutputStream();
			exportExcel.write(outputStream);
			outputStream.flush();
			outputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/**
	 * @Title: getProdunctOrderChart
	 * @Description: 商品订单和项目订单金额占比 返回的字段名必须为value和name
	 * @return
	 * @return: JSONObject
	 * @author: 查恒 2017年4月27日 上午10:03:16
	 */
	@ResponseBody
	@RequestMapping(value = "/productOrderChart")
	public JSONObject getProductOrderChart() {
		JSONObject json = new JSONObject();
		List<Map<String, Object>> productOrderList = tradeMapper.getProductOrderChart();
		String jsonString = JSON.toJSONString(productOrderList, CommonUtil.jsonfilter,
				SerializerFeature.WriteDateUseDateFormat);
		JSONArray fromObject = JSONArray.fromObject(jsonString);
		json.put("data", fromObject);
		return json;
	}

	/**
	 * @Title: getProdunctOrderChart
	 * @Description: 各品类订单金额占比
	 * @return
	 * @return: JSONObject
	 * @author: 查恒 2017年4月27日 上午11:39:15
	 */
	@ResponseBody
	@RequestMapping(value = "/orderTypeTotalPie")
	public JSONObject getOrderTypeTotalPie() {
		JSONObject json = new JSONObject();
		List<Map<String, Object>> orderTypeTotalList = tradeMapper.getOrderTypeTotalPie();
		String jsonString = JSON.toJSONString(orderTypeTotalList, CommonUtil.jsonfilter,
				SerializerFeature.WriteDateUseDateFormat);
		JSONArray fromObject = JSONArray.fromObject(jsonString);
		json.put("data", fromObject);
		return json;
	}

	/**
	 * @Title: getOrderStateChart
	 * @Description: 各状态订单占比
	 * @return
	 * @return: JSONObject
	 * @author: 查恒 2017年4月27日 下午1:11:59
	 */
	@ResponseBody
	@RequestMapping(value = "/orderStateChart")
	public JSONObject getOrderStateChart() {
		JSONObject json = new JSONObject();
		List<Map<String, Object>> orderStateChart = tradeMapper.getOrderStateChart();
		String jsonString = JSON.toJSONString(orderStateChart, CommonUtil.jsonfilter,
				SerializerFeature.WriteDateUseDateFormat);
		JSONArray fromObject = JSONArray.fromObject(jsonString);
		json.put("data", fromObject);
		return json;
	}

	/**
	 * @Title: getViewNumTable
	 * @Description: 当前各品类商品浏览量
	 * @return
	 * @return: JSONObject
	 * @author: 查恒 2017年4月27日 下午1:33:54
	 */
	@ResponseBody
	@RequestMapping(value = "/viewNumTable")
	public JSONObject getViewNumTable() {
		JSONObject json = new JSONObject();
		List<Map<String, Object>> viewNumTable = tradeMapper.getViewNumTable();
		String jsonString = JSON.toJSONString(viewNumTable, CommonUtil.jsonfilter,
				SerializerFeature.WriteDateUseDateFormat);
		JSONArray fromObject = JSONArray.fromObject(jsonString);
		json.put("data", fromObject);
		return json;
	}

	/**
	 * @Title: getBuyerTotalPriceTable
	 * @Description: 当前采购金额排名前十的采购商
	 * @return
	 * @return: JSONObject
	 * @author: 查恒 2017年4月27日 下午1:35:46
	 */
	@ResponseBody
	@RequestMapping(value = "/buyerTotalPriceTable")
	public JSONObject getBuyerTotalPriceTable() {
		JSONObject json = new JSONObject();
		List<Map<String, Object>> buyerTotalPriceTable = tradeMapper.getBuyerTotalPriceTable();
		String jsonString = JSON.toJSONString(buyerTotalPriceTable, CommonUtil.jsonfilter,
				SerializerFeature.WriteDateUseDateFormat);
		JSONArray fromObject = JSONArray.fromObject(jsonString);
		json.put("data", fromObject);
		return json;
	}

	/**
	 * @Title: getSellerTotalPriceTable
	 * @Description: 当前订单金额排名前十的供应商
	 * @return
	 * @return: JSONObject
	 * @author: 查恒 2017年4月27日 下午1:35:49
	 */
	@ResponseBody
	@RequestMapping(value = "/sellerTotalPriceTable")
	public JSONObject getSellerTotalPriceTable() {
		JSONObject json = new JSONObject();
		List<Map<String, Object>> sellerTotalPriceTable = tradeMapper.getSellerTotalPriceTable();
		String jsonString = JSON.toJSONString(sellerTotalPriceTable, CommonUtil.jsonfilter,
				SerializerFeature.WriteDateUseDateFormat);
		JSONArray fromObject = JSONArray.fromObject(jsonString);
		json.put("data", fromObject);
		return json;
	}

	/** 交易概览结束 **/
	@MenuPermission
	@RequestMapping(value = "/tradedetail")
	public String tradedetail(Integer type, ModelMap model) {
		if (type == null) {
			type = 0;
		}
		model.addAttribute("type", type);
		return "trade/trade_list";
	}

	@ResponseBody
	@RequestMapping(value = "/tradedetaildata")
	public JSONObject userdetail(HttpServletRequest request, Integer pageNo, String[] orderBy, Integer type,
			ModelMap model) {
		// 搜索条件
		Map searchMap = RequestUtils.getSearchMap(request);
		JSONObject json = new JSONObject();
		List<Map<String, Object>> selectList = null;
		Page<Object> startPage = null;
		// 列表序号
		if (type == null) {
			type = 0;
		}
		if (type.equals(1)) {
			// 订单列表
			startPage = PageHelper.startPage(pageNo == null ? 1 : pageNo, Globals.PAGE_SIZE);
			selectList = tradeMapper.selectOrderList(searchMap);
		} else if (type.equals(2)) {
			// 已支付订单
			startPage = PageHelper.startPage(pageNo == null ? 1 : pageNo, Globals.PAGE_SIZE);
			selectList = tradeMapper.selectOrderTrade(searchMap);
		}else  if(type.equals(3)){
			//当月客单价
			startPage = PageHelper.startPage(pageNo == null ? 1 : pageNo, Globals.PAGE_SIZE);
			selectList = tradeMapper.selectOrderCustomerTrade(searchMap);
		}else  if(type.equals(4)){
			//采购商交易金额排行
			startPage = PageHelper.startPage(pageNo == null ? 1 : pageNo, Globals.PAGE_SIZE);
			selectList = tradeMapper.getBuyerTotalPrice(searchMap);
		}else  if(type.equals(5)){
			//供应商交易金额排行
			startPage = PageHelper.startPage(pageNo == null ? 1 : pageNo, Globals.PAGE_SIZE);
			selectList = tradeMapper.getSellerTotalPrice(searchMap);
		}else {
			// 订单总数和总额
			startPage = PageHelper.startPage(pageNo == null ? 1 : pageNo, Globals.PAGE_SIZE);
			selectList = tradeMapper.orderAmountCountPreMonth(searchMap);
		}

		Pagination paginationList = paginationService.getPaginationList(startPage, selectList);
		RequestUtils.MapToModelMap(searchMap, request);
		String jsonString = JSON.toJSONString(paginationList.getList(), CommonUtil.jsonfilter,
				SerializerFeature.WriteDateUseDateFormat);
		JSONArray fromObject = JSONArray.fromObject(jsonString);
		json.put("data", fromObject);
		json.put("draw", paginationList.getPageNo());
		json.put("total", paginationList.getTotalCount());
		json.put("recordsTotal", paginationList.getTotalCount());
		json.put("recordsFiltered", paginationList.getTotalCount());
		return json;
	}

	/** excel导出 **/
	@RequestMapping(value = "/exportTradeListExcel")
	public void exportTradeData(Integer type, HttpServletRequest request, HttpServletResponse response) {
		Workbook exportExcel = null;
		Map searchMap = RequestUtils.getSearchMap(request);
		List<Map<String, Object>> selectList = null;
		String title = ".xls";
		if (type.equals(0)) {
			// 订单总数和总额
			selectList = tradeMapper.orderAmountCountPreMonth(searchMap);
			exportExcel = ExcelExportUtil.exportExcel(
					new ExportParams(ExcelExportEntityUtil.TRADE_DETAIL_TITLE, "各月订单金额", "各月订单金额"),
					ExcelExportEntityUtil.orderAmountCountPreMonthList(), selectList);
			title = ExcelExportEntityUtil.TRADE_DETAIL_TITLE + "各月订单金额" + title;
		} else if (type.equals(1)) {
			// 订单列表
			selectList = tradeMapper.selectOrderList(searchMap);
			exportExcel = ExcelExportUtil.exportExcel(
					new ExportParams(ExcelExportEntityUtil.TRADE_DETAIL_TITLE, "订单列表", "订单列表"),
					ExcelExportEntityUtil.selectOrderList(), selectList);
			title = ExcelExportEntityUtil.TRADE_DETAIL_TITLE + "订单列表" + title;
		} else if (type.equals(2)) {
			// 已支付订单
			selectList = tradeMapper.selectOrderTrade(searchMap);
			exportExcel = ExcelExportUtil.exportExcel(
					new ExportParams(ExcelExportEntityUtil.TRADE_DETAIL_TITLE, "支付明细", "支付明细"),
					ExcelExportEntityUtil.orderTradeList(), selectList);
			title = ExcelExportEntityUtil.TRADE_DETAIL_TITLE + "支付明细" + title;
		}else  if(type.equals(3)){
			//当月客单价
			selectList = tradeMapper.selectOrderCustomerTrade(searchMap);
			exportExcel = ExcelExportUtil.exportExcel(
					new ExportParams(ExcelExportEntityUtil.TRADE_DETAIL_TITLE, "各月客单价", "各月客单价"),
					ExcelExportEntityUtil.orderCustomerTradeList(), selectList);
			title = ExcelExportEntityUtil.TRADE_DETAIL_TITLE + "各月客单价" + title;
		}else  if(type.equals(4)){
			//当月客单价
			selectList = tradeMapper.getBuyerTotalPrice(searchMap);
			exportExcel = ExcelExportUtil.exportExcel(
					new ExportParams("采购金额排名", null, "采购金额排名"),
					ExcelExportEntityUtil.bullerPriceList(), selectList);
			title = "安装通采购商采购金额排名" + title;
		}else  if(type.equals(5)){
			//当月客单价
			selectList = tradeMapper.getSellerTotalPrice(searchMap);
			exportExcel = ExcelExportUtil.exportExcel(
					new ExportParams("供应商订单金额排名", null , "供应商订单金额排名"),
					ExcelExportEntityUtil.sellerPriceList(), selectList);
			title = "安装通供应商订单金额排名" + title;
		}

		try {
			response.setContentType("application/vnd.ms-excel;");
			response.setHeader("Content-Disposition", "attachment;filename=" + CommonUtil.toUtf8String(request.getHeader("User-Agent") , title));
			ServletOutputStream outputStream = response.getOutputStream();
			exportExcel.write(outputStream);
			outputStream.flush();
			outputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
